import logger from '../services/logger.js'

export const requestLogger = (req, res, next) => {
  const start = Date.now()
  
  // 请求完成时记录日志
  res.on('finish', () => {
    const duration = Date.now() - start
    logger.info('Request completed', {
      method: req.method,
      url: req.originalUrl,
      status: res.statusCode,
      duration: `${duration}ms`,
      userAgent: req.get('user-agent')
    })
  })
  
  next()
}

export const errorLogger = (err, req, res, next) => {
  logger.error('Request error', {
    error: err.message,
    stack: err.stack,
    method: req.method,
    url: req.originalUrl,
    body: req.body
  })
  next(err)
}

// 性能监控
export const performanceMonitor = (req, res, next) => {
  const start = process.hrtime()
  
  res.on('finish', () => {
    const [seconds, nanoseconds] = process.hrtime(start)
    const duration = seconds * 1000 + nanoseconds / 1000000
    
    if (duration > 1000) { // 记录超过1秒的请求
      logger.warn('Slow request detected', {
        method: req.method,
        url: req.originalUrl,
        duration: `${duration.toFixed(2)}ms`
      })
    }
  })
  
  next()
} 